'''
获取竞猜官网的赔率变化数据
保存到mysql数据库中

'''

'''
获取数据
'''

import requests
import json
from bs4 import BeautifulSoup
import datetime
from loaddata.mgDB import JinCaiDatabase, Wan500Database
from loaddata import load_ouzhi

'''
下载竞猜数据
'''


class LoadDataJinCai:
    def __init__(self, t):
        self.mgdb = JinCaiDatabase(t)

    '''
    爬取数据
    '''

    def gethtml(self, url):
        res = requests.get(url)
        res.encoding = "utf-8"
        return res.text

    # 获取开奖详情
    def getfixedBonus(self, matchId):
        print("正在下载", matchId, "的数据")
        url = "https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry?clientCode=3001&matchId={}".format(
            matchId)
        data = self.gethtml(url)
        res = json.loads(data)
        return res.get("value")

    # 获取每30天的历史数据
    def getdatas(self, s, e):
        print("正在下载", s, "到", e, "的数据")
        url = "https://webapi.sporttery.cn/gateway/jc/football/getMatchResultV1.qry?" \
              "matchPage=1&matchBeginDate={}&matchEndDate={}&leagueId=&pageSize=10000&pageNo=1&isFix=0&pcOrWap=0".format(
            s, e)
        data = self.gethtml(url)
        result = json.loads(data)
        matchResultList = result.get("value").get("matchResult")
        rs = []
        for m in matchResultList:
            matchDate = m.get("matchDate")
            matchNum = m.get("matchNum")
            no = int(matchNum) // 1000
            mdate = datetime.datetime.strptime(matchDate, '%Y-%m-%d')
            # 将日期转换为星期对应的数字（0表示周一）
            weekday_number = mdate.weekday() + 1
            # 修改开奖日期及比赛，保证竞猜日期与场次一致，方便查看
            if weekday_number != no:
                mdate -= datetime.timedelta(days=1)
                date_str = mdate.strftime("%Y-%m-%d")
                m["matchTime"] = date_str
            else:
                m["matchTime"] = matchDate
            # 添加一个场次唯一（场次日期+场次编码）
            m["matchNo"] = f"{m.get('matchTime')}{matchNum}"

            flag = self.mgdb.get_jincai_config({"key": "updata_flag"})
            # 判断是否已经下载,已经存在，就不添加了
            if flag.get("setValue").get(m.get("matchNo")):
                continue
            else:
                m["fixedBonus"] = self.getfixedBonus(m.get("matchId"))
                rs.append(m)
        return rs

    # 保持到数据库
    def save(self, ds):
        self.mgdb.batch_sava_to_jincai(ds)

    # 竞猜网下载受关注的比赛（正在售卖的场次）
    def getSelling(self):
        url = "https://webapi.sporttery.cn/gateway/jc/football/getMatchListV1.qry?clientCode=3001"
        data = self.gethtml(url)
        res = json.loads(data)
        self.mgdb.savaOrUpdataSelling(res)


'''
保存数据mysql
'''
import mysql.connector


class mysqlDB():
    def __init__(self):
        # 连接到MySQL数据库
        self.conn = mysql.connector.connect(
            host='localhost',  # 替换为你的MySQL服务器地址
            user='root',  # 替换为你的数据库用户名
            password='123456',  # 替换为你的数据库密码
            database='caipiao'  # 替换为你的数据库名
        )

    def save(self):
        # 创建一个cursor对象
        cursor = self.conn.cursor()
        # 插入数据的SQL语句
        add_data_sql = """
        INSERT INTO your_table_name (column1, column2, column3)
        VALUES (%s, %s, %s)
        """
        # 要插入的数据
        data = ('value1', 'value2', 'value3')
        # 执行SQL语句
        cursor.execute(add_data_sql, data)
        # 提交事务
        self.conn.commit()
        # 关闭cursor和连接
        cursor.close()
        self.conn.close()


# 比赛表
class MatchInfoModel():
    def __init__(self, matchId, matchTime, matchNum, matchNumStr, allAwayTeam, allHomeTeam, sectionsNo1, sectionsNo999,
                 winFlag, matchStatus):
        self.matchId = matchId  # 比赛id
        self.matchTime = matchTime  # 比赛时间
        self.matchNum = matchNum  # 竞猜编号
        self.matchNumStr = matchNumStr  # 竞猜编号中文
        self.allAwayTeam = allAwayTeam  # 客队
        self.allHomeTeam = allHomeTeam  # 主队
        self.sectionsNo1 = sectionsNo1  # 半场比分
        self.sectionsNo999 = sectionsNo999  # 全场比分 最终比赛结果，H主赢，D平，A客赢
        self.matchStatus = matchStatus  # 比赛状态 比赛状态，Selling正在售卖，over比赛结束，Define未开卖
        self.winFlag = winFlag  # 最终比赛结果，H主赢，D平，A客赢


    def sava(self):
        pass

# 比赛赔率数据表
class Oddshistory():
    def __init__(self,matchId,mtype,updateTime,H,D,A):
        self.matchId = matchId
        self.mtype = mtype  # hhad让球胜平负，had胜平负
        self.updateTime = updateTime
        self.H = H  # 胜赔率
        self.D = D  # 平赔率
        self.A = A  # 负赔率

    def sava(self):
        pass
